// pages/Charisma/Charisma.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 'follow', // 默认选中"关注"
    followPosts: [],  // 关注内容
    recommendPosts: [], // 推荐内容
    latestPosts: [],  // 最新内容
    newestPosts: [] ,// 新增：存储最新发布的内容
    needRefresh: false,
    isFullText: false, // 控制是否显示全文
    moments: [
      {
        id: 1,
        username: '张三',
        avatar: '/images/friend.png',
        content: '今天天气真好，出去走走心情舒畅！',
        images: ['/images/erhai.jpg'],
        time: '2小时前',
        liked: false,
        likes: [],
        collected: false,
        comments: [],
        showCommentInput: false,
        commentContent: ''
      },
      {
        id: 2,
        username: '李四',
        avatar: '/images/yanglao.png',
        content: '分享一个健康小贴士：每天喝8杯水，保持身体水分充足。',
        images: ['/images/erhai.jpg'],
        time: '4小时前',
        liked: true,
        likes: ['我', '王五'],
        collected: false,
        comments: [
          {
            id: 1,
            content: '很实用的建议！',
            username: '我',
            time: '刚刚',
            avatar: '/images/friend.png'
          },
          {
            id: 2,
            content: '我也要试试',
            username: '王五',
            time: '1小时前',
            avatar: '/images/yanglao.png'
          }
        ],
        showCommentInput: false,
        commentContent: ''
      },
      {
        id: 3,
        username: '王五',
        avatar: '/images/friend.png',
        content: '今天参加了社区的健康讲座，学到了很多养生知识，感觉收获满满！',
        images: [],
        time: '6小时前',
        liked: false,
        likes: [],
        collected: false,
        comments: [
          {
            id: 3,
            content: '下次我也要去参加！',
            username: '我',
            time: '2小时前',
            avatar: '/images/friend.png'
          }
        ],
        showCommentInput: false,
        commentContent: ''
      },
      {
        id: 4,
        username: '赵六',
        avatar: '/images/yanglao.png',
        content: '和朋友们一起跳广场舞，身体越来越健康了！',
        images: ['/images/erhai.jpg', '/images/erhai.jpg'],
        time: '8小时前',
        liked: true,
        likes: ['我', '张三', '李四'],
        collected: true,
        comments: [
          {
            id: 4,
            content: '看起来很开心！',
            username: '我',
            time: '3小时前',
            avatar: '/images/friend.png'
          },
          {
            id: 5,
            content: '下次叫上我一起！',
            username: '张三',
            time: '4小时前',
            avatar: '/images/friend.png'
          }
        ],
        showCommentInput: false,
        commentContent: ''
      }
    ],
    postList: [
        {
          id: 1,
          avatar: '/images/avatar1.png',
          userName: '明仁聪明的小温',
          content: '服务态度很好 服务热情，耐心帮忙搭配 衣服质量也不错...',
          image: '/images/post1.jpg',
          isFollowed: false, // 关注状态
          likeCount: 63,
          isLiked: false,
          isStarred: false
        },
        {
          id: 2,
          avatar: '/images/avatar2.png',
          userName: '时尚达人',
          content: '今天发现一家超棒的买手店，分享给大家...',
          image: '/images/post2.jpg',
          isFollowed: true, // 已关注状态
          likeCount: 45,
          isLiked: false,
          isStarred: false
        }
      ],
      bannerList: [
        'https://img.shetu66.com/2023/10/05/1696480719857444.png',
        'https://img.shetu66.com/2023/08/30/1693379443930617.png',
        'https://imgs.design006.com/202303/Design006_4ziGZZwxkn.png?x-oss-process=style/prev_w_460_mh_1600',
        
      ],
      postList: [
        {
          id: 1,
          imgUrl: "https://ts4.tc.mm.bing.net/th/id/OIP-C.C_HIQhMn7QEF9470A86ZDgHaEK?rs=1&pid=ImgDetMain&o=7&rm=3", // 本地图片路径，需放到项目的 images 目录；也可填网络图片地址
          title: "工作日去路易威登游轮，预约有点难",
          author: "XY821216",
          likeCount: 63
        },
        {
          id: 2,
          imgUrl: "https://ts3.tc.mm.bing.net/th/id/OIP-C.aRWPDplKNfmQECbLCBYY7AHaHq?rs=1&pid=ImgDetMain&o=7&rm=3",
          title: "一直不懂....",
          author: "人间小...",
          likeCount: 45
        },
        {
          id: 3,
          imgUrl: "https://ts2.tc.mm.bing.net/th/id/OIP-C.J6F-PbYsWm3K_RhrAXjV4wHaE7?rs=1&pid=ImgDetMain&o=7&rm=3",
          title: "周末去哪玩这是个问题",
          author: "儿童成长馆",
          likeCount: 100
        },
        {
          id: 4,
          imgUrl: "https://ts1.tc.mm.bing.net/th/id/OIP-C.YUxmcNdEPvJhWltGVHs6yQHaHa?rs=1&pid=ImgDetMain&o=7&rm=3",
          title: "Labubu家族全科普，这下",
          author: "潮玩达人",
          likeCount: 88
        },
        {
            id: 5,
            imgUrl: "https://ts4.tc.mm.bing.net/th/id/OIP-C.C_HIQhMn7QEF9470A86ZDgHaEK?rs=1&pid=ImgDetMain&o=7&rm=3", // 本地图片路径，需放到项目的 images 目录；也可填网络图片地址
            title: "工作日去路易威登游轮，预约有点难",
            author: "XY821216",
            likeCount: 63
          },
          {
            id: 6,
            imgUrl: "https://ts3.tc.mm.bing.net/th/id/OIP-C.aRWPDplKNfmQECbLCBYY7AHaHq?rs=1&pid=ImgDetMain&o=7&rm=3",
            title: "一直不懂....",
            author: "人间小...",
            likeCount: 45
          },
          {
            id: 7,
            imgUrl: "https://ts2.tc.mm.bing.net/th/id/OIP-C.J6F-PbYsWm3K_RhrAXjV4wHaE7?rs=1&pid=ImgDetMain&o=7&rm=3",
            title: "周末去哪玩这是个问题",
            author: "儿童成长馆",
            likeCount: 100
          },
          {
            id: 8,
            imgUrl: "https://ts1.tc.mm.bing.net/th/id/OIP-C.YUxmcNdEPvJhWltGVHs6yQHaHa?rs=1&pid=ImgDetMain&o=7&rm=3",
            title: "Labubu家族全科普，这下",
            author: "潮玩达人",
            likeCount: 88
          }
          
      ],
      activity: [
        {
          id: 1,
          image: "https://vcg01.cfp.cn/creative/vcg/800/new/VCG211428489532.jpg", // 替换为实际图片路径，可放本地或网络地址
          title: "书法唱"
        },
        {
          id: 2,
          image: "https://ts1.tc.mm.bing.net/th/id/R-C.87b6c47a39d9f8cbce5319c146919cbe?rik=pwyee9paWiqOFg&riu=http%3a%2f%2fyztv-vod.homecdn.com%2fbutelvod%2fe657234d-6406-4daf-9a41-14d79fcb94bc.jpeg%3fcmd%3dimageprocess%2fformat%2fjpg%2fprocesstype%2f2%2fwidth%2f720%2fquality%2f80&ehk=CHvHmMSU9msZlqukl7E9nHstd8I2v9PQLwMa4fxN6XA%3d&risl=&pid=ImgRaw&r=0",
          title: "称唱"
        },
        {
          id: 3,
          image: "https://ts1.tc.mm.bing.net/th/id/R-C.f0ce50f4868aa3f78fcc5b2b5fabcceb?rik=7bq2FYXqcMEaEQ&riu=http%3a%2f%2fimg1.voc.com.cn%2fUpLoadFile%2f2019%2f06%2f06%2f201906061716319439.jpg&ehk=RKqx6AU6l1bWn%2f8h1JW93eZwEDYo0%2beLRTOmFRUZ07w%3d&risl=&pid=ImgRaw&r=0",
          title: "广场舞"
        },
    ],
      activitiesList:[
        'https://img.shetu66.com/2023/10/05/1696480719857444.png',
        'https://img.shetu66.com/2023/10/27/1698418822738795.png',
        'https://imgs.design006.com/202303/Design006_4ziGZZwxkn.png?x-oss-process=style/prev_w_460_mh_1600',
        'https://ts1.tc.mm.bing.net/th/id/OIP-C.wS6p9eWV3pEhmu5B-UW_qgHaHa?rs=1&pid=ImgDetMain&o=7&rm=3'

        
    ],
      // 模拟从接口获取的动态数据列表，实际可替换为真实接口返回数据
    dynamicList: [
        {
          id: 1,
          imgUrl: "https://ts3.tc.mm.bing.net/th/id/OIP-C.oTlzfP7zbVK9tfXJM2yBiQHaE8?rs=1&pid=ImgDetMain&o=7&rm=3", // 本地图片路径，需在项目中对应位置放置图片
          content: "上海！我最怕倒闭的一家店！！",
          author: "余子酱",
          likeCount: 14
        },
        {
          id: 2,
          imgUrl: "https://n.sinaimg.cn/sinacn20/215/w2048h1367/20180815/aa03-hhtfwqr8397759.jpg",
          content: "真的不输给火烧云！",
          author: "Joy",
          likeCount: 21
        },
        {
          id: 3,
          imgUrl: "https://img1.qunarzz.com/travel/d6/1510/34/d5cd72f7929e88.jpg",
          content: "超有氛围的中式茶馆",
          author: "茶友小张",
          likeCount: 30
        },
        {
          id: 4,
          imgUrl: "https://ts4.tc.mm.bing.net/th/id/OIP-C.2-dGpRZg58faJjATS080gAHaE8?rs=1&pid=ImgDetMain&o=7&rm=3",
          content: "宝藏韩料店分享",
          author: "美食小探",
          likeCount: 25
        }
      ]
  }, 

  // 显示/隐藏全文
  toggleFullText() {
    this.setData({
      isFullText: !this.data.isFullText
    })
    // 实际可根据状态加载完整文本内容
  },

  // 切换评论输入框显隐
  toggleCommentInput(e) {
    const momentId = e.currentTarget.dataset.id;
    const moments = this.data.moments.map(moment => {
      if (moment.id === momentId) {
        return {
          ...moment,
          showCommentInput: !moment.showCommentInput,
          commentContent: moment.showCommentInput ? "" : moment.commentContent // 关闭时清空内容
        };
      }
      return moment;
    });
    
    this.setData({ moments });
    
    // 如果打开输入框，自动聚焦
    const targetMoment = moments.find(item => item.id === momentId);
    if (targetMoment && targetMoment.showCommentInput) {
      setTimeout(() => {
        wx.createSelectorQuery()
          .select(`#commentInput-${momentId}`)
          .focus()
          .exec();
      }, 100);
    }
  },

  // 监听评论输入
  onCommentInput(e) {
    const momentId = e.currentTarget.dataset.id;
    const content = e.detail.value;
    const moments = this.data.moments.map(moment => {
      if (moment.id === momentId) {
        return {
          ...moment,
          commentContent: content
        };
      }
      return moment;
    });
    
    this.setData({ moments });
  },

    // 发送评论
  sendComment(e) {
    const momentId = e.currentTarget.dataset.id;
    const moments = this.data.moments.map(moment => {
      if (moment.id === momentId) {
        if (moment.commentContent && moment.commentContent.trim()) {
          const newComment = {
            id: Date.now(),
            content: moment.commentContent.trim(),
            username: '我',
            time: '刚刚',
            avatar: '/images/friend.png',
            replyTo: moment.replyTo || null
          };
          
          return {
            ...moment,
            comments: [...moment.comments, newComment],
            commentContent: "",
            showCommentInput: false,
            replyTo: null
          };
        }
        return moment;
      }
      return moment;
    });
    
    this.setData({ moments });
    
    // 保存到本地存储
    wx.setStorageSync('moments', moments);
    
    wx.showToast({
      title: '评论成功',
      icon: 'success',
      duration: 1500
    });
  },

  // 取消回复状态
  cancelReply(e) {
    const momentId = e.currentTarget.dataset.id;
    const moments = this.data.moments.map(moment => {
      if (moment.id === momentId) {
        return {
          ...moment,
          showCommentInput: false,
          commentContent: "",
          replyTo: null
        };
      }
      return moment;
    });
    
    this.setData({ moments });
  },

  // 回复评论
  replyComment(e) {
    const { momentId, commentId } = e.currentTarget.dataset;
    const moment = this.data.moments.find(item => item.id === momentId);
    const comment = moment.comments.find(item => item.id === commentId);
    
    // 设置回复状态
    const moments = this.data.moments.map(m => {
      if (m.id === momentId) {
        return {
          ...m,
          showCommentInput: true,
          commentContent: `回复 @${comment.username}：`,
          replyTo: commentId
        };
      }
      return m;
    });
    
    this.setData({ moments });
    
    // 自动聚焦到输入框
    setTimeout(() => {
      wx.createSelectorQuery()
        .select(`#commentInput-${momentId}`)
        .focus()
        .exec();
    }, 100);
  },

  // 长按评论删除
  longPressComment(e) {
    const { momentId, commentId } = e.currentTarget.dataset;
    const moment = this.data.moments.find(item => item.id === momentId);
    const comment = moment.comments.find(item => item.id === commentId);
    
    // 只有自己的评论才能删除
    if (comment.username === '我') {
      wx.showModal({
        title: '删除评论',
        content: '确定要删除这条评论吗？',
        success: (res) => {
          if (res.confirm) {
            this.deleteComment(e);
          }
        }
      });
    } else {
      wx.showToast({
        title: '只能删除自己的评论',
        icon: 'none'
      });
    }
  },
  goJoincoin() {
    wx.navigateTo({ url: '/pages/joined/joincoin' });
  },
  // 转发功能
  shareMoment(e) {
    const id = e.currentTarget.dataset.id;
    const moments = this.data.moments;
    const moment = moments.find(m => m.id === id);
    
    wx.showActionSheet({
      itemList: ['转发给朋友', '分享到朋友圈'],
      success(res) {
        if (res.tapIndex === 0) {
          wx.showToast({
            title: '已转发给朋友',
            icon: 'success'
          });
        } else if (res.tapIndex === 1) {
          wx.showToast({
            title: '已分享到朋友圈',
            icon: 'success'
          });
        }
      }
    });
  },

  // 删除评论
  deleteComment(e) {
    const { momentId, commentId } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          const moments = this.data.moments.map(moment => {
            if (moment.id === momentId) {
              return {
                ...moment,
                comments: moment.comments.filter(comment => comment.id !== commentId)
              };
            }
            return moment;
          });
          
          this.setData({ moments });
          wx.setStorageSync('moments', moments);
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 转发逻辑（这里只是演示，实际需结合需求做复制、调微信转发 API 等）
  forwardMoment(e) {
    const momentId = e.currentTarget.dataset.id;
    // 简单提示，若要真转发：
    // 1. 复制内容：可把朋友圈文字、图片拼好，调用 wx.setClipboardData 复制
    // 2. 调微信转发 API：wx.showShareMenu + onShareAppMessage 配置转发内容
    wx.showToast({
      title: '转发功能可自定义实现',
      icon: 'none'
    });
    // 示例：调微信官方转发（需页面配置 onShareAppMessage）
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 若用官方转发，需在页面 js 加这个函数，配置转发内容
  onShareAppMessage(e) {
    const momentId = e.target.dataset.id;
    const currentMoment = this.data.moments.find(item => item.id === momentId);
    return {
      title: '转发的标题',
      path: `/pages/momentDetail/momentDetail?id=${momentId}`, // 转发跳转路径
      imageUrl: currentMoment.images[0] // 转发封面图
    };
  },

  // Tab 切换方法
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },
  
  // 前往发布页面逻辑（可根据实际调整）
  goPublish() {
    wx.showToast({
      title: '前往发布页面',
      icon: 'none'
    });
    // 实际可使用 wx.navigateTo 跳转，如：
    wx.navigateTo({ url: '/pages/publish/publish' });
  },

  // 预览图片
  previewImage(e) {
    const current = e.currentTarget.dataset.img;
    const urls = e.currentTarget.dataset.imgList;
    
    wx.previewImage({
      current: current,
      urls: urls
    });
  }, 
  // 点赞功能
  likeMoment(e) {
    const momentId = e.currentTarget.dataset.id;
    const updatedMoments = this.data.moments.map(moment => {
      if (moment.id === momentId) {
        // 切换点赞状态
        const newLiked = !moment.liked;
        let newLikes = [...moment.likes];
        
        if (newLiked) {
          // 点赞，添加当前用户
          if (!newLikes.includes('我')) {
            newLikes.push('我');
          }
        } else {
          // 取消点赞，移除当前用户
          newLikes = newLikes.filter(like => like !== '我');
        }
        
        return {
          ...moment,
          liked: newLiked,
          likes: newLikes
        };
      }
      return moment;
    });

    // 更新数据并保存到本地存储
    this.setData({ moments: updatedMoments });
    wx.setStorageSync('moments', updatedMoments);
  },

  
  // 显示评论（简化版）
  showComment(e) {
    wx.showModal({
      title: '评论',
      content: '评论功能将在后续版本中实现',
      showCancel: false
    });
  },
  
  // 加载最新内容
  loadLatestPosts() {
    const posts = wx.getStorageSync('posts') || [];
    this.setData({ latestPosts: posts });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      // 从本地存储加载朋友圈数据
      const storedMoments = wx.getStorageSync('moments') || this.data.moments;
      this.setData({
        moments: storedMoments
      });
    

  },

  // 新增：删除发布内容
  deletePost(e) {
    const postId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '删除后无法恢复，是否确认？',
      success: (res) => {
        if (res.confirm) {
          // 从本地存储删除
          const posts = wx.getStorageSync('posts') || [];
          const newPosts = posts.filter(item => item.id !== postId);
          wx.setStorageSync('posts', newPosts);
          
          // 刷新页面
          this.loadNewestPosts();
          wx.showToast({ title: '删除成功' });
        }
      }
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // if (this.data.needRefresh) {
    //     this.loadNewestPosts();
    //     this.setData({ needRefresh: false }); // 重置标记
    //   }
    const storedMoments = wx.getStorageSync('moments') || this.data.moments;
      this.setData({
        moments: storedMoments
      });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})